package com.third.device.mg.serialport.service

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import com.third.device.mg.serialport.help.netty.BootstrapManager
import com.third.device.mg.serialport.listener.MGNettyConnectListener
import org.jetbrains.annotations.NotNull

/**
 * company 广东玛格家居有限公司
 * @author smoker
 * @Date 2021/12/29
 * Description:Socket 连接所在的  服务
 * 统一管理Socket的连接
 */
class MGSocketService : Service() {

    private lateinit var nettyManager: BootstrapManager

    var isBind = false
    companion object {
        private lateinit var mService: MGSocketService
        fun get(): MGSocketService {
            return if (this::mService.isInitialized) {
                mService
            } else {
                //throw ExceptionInInitializerError(Throwable("服务未启动"))
                MGSocketService()
            }
        }
    }

    inner class MGSocketServiceBinder : Binder() {
        fun getService(): MGSocketService = mService
    }

    override fun onCreate() {
        super.onCreate()
        isBind = true
        mService = this
        nettyManager = BootstrapManager()
    }

    override fun onBind(intent: Intent?): IBinder = MGSocketServiceBinder()

    override fun onUnbind(intent: Intent?): Boolean {
        isBind = false
        nettyManager.onDestroy()
        return super.onUnbind(intent)
    }

    /**
     * 检查是否已经连接
     */
    fun checkConnect(@NotNull ip:String ,port:Int) = nettyManager.checkConnect(ip ,port)


    /**
     * 连接Socket
     * @param ip   目标IP地址
     * @param port 目标端口
     */
    fun connectNetty(@NotNull ip:String ,port:Int){
        nettyManager.createClient(ip ,port)
    }

    /**
     * 写入数据
     * @param ip   目标IP地址
     * @param port 目标端口
     * @param content 写入的内容
     */
    fun write(@NotNull ip:String, port:Int, content:ByteArray){
        nettyManager.write(ip ,port ,content)
    }


    /**
     * 销毁Socket
     * @param ip   目标IP地址
     * @param port 目标端口
     */
    fun disconnect(@NotNull ip:String ,port:Int){
        nettyManager.onDestroy(ip ,port)
    }



    /**
     * 销毁所有Socket
     */
    fun disconnectAll(){
        nettyManager.onDestroy()
    }


    /**
     * 设置监听事件
     * @param listener @see[MGNettyConnectListener]
     */
    fun setListener(listener:MGNettyConnectListener){
        nettyManager.setListener(listener)
    }

}